import React, { useEffect, useRef, useState } from 'react';
import listPlugin from '@fullcalendar/list';
import FullCalendar from '@fullcalendar/react';
import dayGridPlugin from '@fullcalendar/daygrid';
import timeGridPlugin from '@fullcalendar/timegrid';
import interactionPlugin from '@fullcalendar/interaction';
import FormModal from '@/component/FormModal';
import { useFormDialog } from '@/hooks/useForm';
import { DatePicker, Select, TimePicker } from 'antd';
import dayjs from 'dayjs';
import { arrange, findClassInfo } from '@/views/attendance/classInfo/api';
import { page as pageStaff } from '@/views/employee/staff/api';
import { getTenantId } from '@/utils/storage';
import Detail from '@/views/attendance/classInfo/detail/index';
import { useClassDetail } from '@/views/attendance/classInfo/hooks/useClassDetail';
import { buildArrangeModel } from '@/views/attendance/classInfo/data';
import StaffView from '@/views/attendance/classInfo/staff';
import './index.less';

const ClassInfo = () => {

    const calendarRef = useRef(null);
    // 日历事件
    const [calendarEvents, setCalendarEvents] = useState([]);
    // 视图切换
    const [changeView, setChangeView] = useState(false);

    // 切换视图
    const onChangeViewHandler = () => {
        setChangeView(!changeView);
    }

    // -------------------
    // --- 临时排班表单 ---
    // -------------------

    // 员工下拉多选
    const [staffOptions, setStaffOptions] = useState([]);
    const onSearchStaffHandler = (val) => {
        let query = {
            params: [
                { field: 'tenantId', value: getTenantId() },
                { field: 'name', expr: 'LIKE_LEFT', value: val },
            ]
        };
        pageStaff(query).then(resp => {
            let options = resp?.data?.records.map(item => ({
                label: item.name,
                value: item.id,
            }));
            setStaffOptions(options);
        });
    }

    const onTemporaryFormCallback = (model) => {
        let params = {
            type: 'temporary',
            data: buildArrangeModel(model),
        };

        temporaryForm.onSubmit(params, onRefreshCalendarCallback);
    }

    const temporaryForm = useFormDialog({
        title: '临时排班',
        width: 450,
        save: arrange,
        callback: onTemporaryFormCallback,
        items: [
            {
                label: '名称',
                name: 'name',
                rules: [{ required: true, message: '请输入名称' }],
            },
            {
                label: '颜色',
                name: 'color',
            },
            {

                label: '日期',
                name: 'workDate',
                rules: [{ required: true, message: '请选择日期' }],
                render: <DatePicker.RangePicker format="YYYY-MM-DD" style={{ width: '100%' }} />,
            },
            {
                label: '时间',
                name: 'workTime',
                rules: [{ required: true, message: '请选择时间' }],
                render: <TimePicker.RangePicker changeOnScroll needConfirm={false} format="HH:mm" style={{ width: '100%' }} />,
            },
            {
                label: '员工',
                name: 'staffIds',
                rules: [{ required: true, message: '请选择员工' }],
                render: <Select
                    mode="multiple"
                    showSearch
                    allowClear
                    placeholder="请选择员工"
                    optionFilterProp="label"
                    filterOption={false}
                    // maxTagCount='responsive'
                    onSearch={(val) => onSearchStaffHandler(val)}
                    options={staffOptions}
                />
            },
        ],
    });



    const onRefreshCalendarCallback = (model) => {
        setStaffOptions([]);
        refreshCalendarEvents(model?.data?.workdays[0]);
    }

    // 日历顶部工具栏
    const headerTools = {
        left: 'staffView prev,next',
        center: 'title',
        right: 'today dayGridMonth,timeGridWeek,timeGridDay'
    };

    // 日历工具栏汉化展示
    const headerToolText = {
        today: '今天',
        month: '月',
        week: '周',
        day: '日'
    }

    // 自定义按钮
    const customButton = {
        staffView: {
            text: '视图',
            // icon: '',
            click: () => {
                onChangeViewHandler();
            }
        }
    }

    // 日历视图
    const calendarViews = {
        timeGridWeek: {
            allDaySlot: false,
            // slotDuration: '00:15',
            // slotLabelInterval: '00:30',
            slotLabelFormat: {
                hour: '2-digit',
                minute: '2-digit',
            },
        },
        timeGridDay: {
            allDaySlot: false,
            // slotDuration: '00:15',
            slotLabelFormat: {
                hour: '2-digit',
                minute: '2-digit',
            },
        },
    };

    const handleEventClick = (info) => {
        info.jsEvent.preventDefault(); // 阻止默认行为
        // let id = info.event.id;
        let event = calendarEvents.find(item => item.id === info.event.id);
        detail.setSelectedEvent(event);
    };

    // 日期点击事件
    const calendarDateClickHandle = (info) => {
        info.jsEvent.preventDefault(); // 阻止默认行为

        // 重置detail组件
        let currentDate = dayjs(info.date).format('YYYY-MM-DD');
        detail.setDate(currentDate);
        detail.setSelectedEvent(null);
        let events = calendarEvents.filter(item => item.date === currentDate);
        detail.setEvents(events);

        // 判断是否需要弹框
        const calendarView = getCalendarView();
        if (calendarView.type !== 'dayGridMonth' || events?.length === 0) {
            temporaryClassHandler(info.date);
        }
    }

    /**
     * 临时排班表单弹框
     * @param date 日期类型
     */
    const temporaryClassHandler = (date) => {
        let work_date = dayjs(date);
        let work_time = work_date;

        const calendarView = getCalendarView();
        if (calendarView.type === 'dayGridMonth') {
            work_time = dayjs(new Date());
        }

        let model = {
            workDate: [work_date, work_date],
            workTime: [work_time, work_time.add(30, 'm')],
        }
        temporaryForm.isOpenDialog(model);
    };

    const getCalendarView = () => {
        return calendarRef.current?.getApi().view;
    }

    /**
     * 刷新日历视图
     * 
     * 相关文档[https://fullcalendar.io/docs/view-object]
     */
    const refreshCalendarEvents = (date = undefined) => {
        if (!calendarRef.current) {
            return;
        }
        date = date || dayjs().format('YYYY-MM-DD');

        const calendarView = getCalendarView();
        let query = {
            startDate: dayjs(calendarView.activeStart).format('YYYY-MM-DD'),
            endDate: dayjs(calendarView.activeEnd).add(-1, 'd').format('YYYY-MM-DD'),
        };
        findClassInfo(query).then(resp => {
            // 全部事件
            let events = [];
            // 排班明细事件
            let selectedEvents = [];
            resp?.data?.forEach((each) => {
                let detail = {
                    id: each.id,
                    date: each.workDate,
                    staffs: each.staffs,
                    beginTime: dayjs(each.startTime, 'HH:mm:ss').format('HH:mm'),
                    finishTime: dayjs(each.endTime, 'HH:mm:ss').format('HH:mm'),
                    title: each.name,
                    start: each.workDate + ' ' + each.startTime,
                    end: each.workDate + ' ' + each.endTime,
                    // textColor: '#000',
                    backgroundColor: each.color,
                    borderColor: each.color,
                    editable: false,
                };
                events.push(detail);
                if (each.workDate === date) {
                    selectedEvents.push(detail);
                }
            });
            setCalendarEvents(events);
            // 初始化detail组件
            detail.setDate(date);
            detail.setSelectedEvent(null);
            detail.setEvents(selectedEvents);
        });
    }

    // 右侧排班详情区域展示
    const detail = useClassDetail({
        callback: refreshCalendarEvents,
    });

    useEffect(() => {
        if (!changeView) {
            refreshCalendarEvents();
        }
    }, [changeView]);

    return (
        <div>
            {changeView ?
                <StaffView callback={onChangeViewHandler}/> :
                (<div style={{ padding: 12, display: 'flex', gap: 20, height: 'calc(100vh - 146px)' }}>
                    {/* 左侧日历区域 */}
                    <div style={{ width: '58%', overflow: 'hidden' }}>
                        <FullCalendar
                            ref={calendarRef}
                            height={'calc(100vh - 172px)'}
                            locale="zh-cn"
                            eventColor="#4285f4"
                            headerToolbar={headerTools}
                            customButtons={customButton}
                            buttonText={headerToolText}
                            dayHeaderFormat={{ weekday: 'short' }}
                            views={calendarViews}
                            navLinks={true}
                            editable={true}
                            firstDay={0}
                            plugins={[dayGridPlugin, timeGridPlugin, listPlugin, interactionPlugin]}
                            initialView="dayGridMonth"
                            dateClick={calendarDateClickHandle}
                            eventClick={handleEventClick}
                            events={calendarEvents}
                            selectable={true}
                        />
                        <FormModal props={temporaryForm} />
                    </div>

                    {/* 右侧事件详情区域 */}
                    <Detail props={detail} />
                </div>)}
        </div>
    );
};

export default ClassInfo;